package com.hxd.common.exception.handler;

import java.util.stream.Collectors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import com.hxd.common.Result;
import com.hxd.common.exception.base.BaseException;

/**
 * 全局异常处理器
 *
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
	
	private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
	
	/**
     * 系统异常
     */
	@ExceptionHandler(Exception.class)
	public Result handleException(Exception e) {
		log.error(e.getMessage(), e);
		return Result.error("服务器错误，请联系管理员");
	}
	
	/**
     * 拦截未知的运行时异常
     */
    @ExceptionHandler(RuntimeException.class)
    public Result runtimeException(RuntimeException e) {
        log.error("运行时异常:", e);
        return Result.error("运行时异常:" + e.getMessage());
    }
    
    /**
     * 自定义基础异常拦截
     */
    @ExceptionHandler(BaseException.class)
    public Result baseException(BaseException e) {
        log.error("操作异常:", e);
        return Result.failure(e.getCode(), e.getMsggess());
    }
    
    /**
     * @Validated 异常拦截
     */
    @ExceptionHandler(value=MethodArgumentNotValidException.class)
	public Result MethodArgumentNotValidHandler(MethodArgumentNotValidException e) {
    	String message = e.getBindingResult().getAllErrors().stream().map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.joining());
    	log.error("验证异常:", e);
		return Result.failure(message);
	}
    
}

